import sys
from datetime import datetime
from PySide6.QtCore import QDate, QTimer
from PySide6.QtWidgets import QFrame, QApplication, QAbstractItemView, QMessageBox, QFileDialog

from backend.db.database import export_member, export_transaction, export_member_certificate
from front.ui.ui_export_excel import Ui_Frame


def combine_time(time, num):
    """整合时间"""
    if num == 0:
        time = datetime.combine(time, datetime.min.time())
    elif num == 1:
        time = datetime.combine(time, datetime.max.time())
    return time


class ExportExcel(Ui_Frame, QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.checkBox.toggled.connect(self.set_dateEdit)
        self.checkBox.setChecked(True)
        self.dateEdit.setDate(QDate.currentDate().addDays(-7))
        self.dateEdit_2.setDate(QDate.currentDate())
        self.start_date = combine_time(self.dateEdit.date().toPython(), 0)
        self.end_date = combine_time(self.dateEdit_2.date().toPython(), 1)
        self.dateEdit.dateChanged.connect(lambda: QTimer.singleShot(0, self.check_dateEdit))
        self.dateEdit_2.dateChanged.connect(lambda: QTimer.singleShot(0, self.check_dateEdit))
        self.set_comboBox()
        self.pushButton.clicked.connect(self.exp_excel)
        self.comboBox.currentIndexChanged.connect(self.switch_combobox)
        self.dateEdit.setEnabled(False)
        self.dateEdit_2.setEnabled(False)
        self.checkBox.setEnabled(False)

    def set_dateEdit(self):
        print("调用了")
        if self.checkBox.isChecked():
            self.dateEdit.setDate(QDate.currentDate().addDays(-7))
            self.dateEdit_2.setDate(QDate.currentDate())
            self.start_date = combine_time(self.dateEdit.date().toPython(), 0)
            self.end_date = combine_time(self.dateEdit_2.date().toPython(), 1)
            self.dateEdit.setEnabled(True)
            self.dateEdit_2.setEnabled(True)
        else:
            print("归零了")
            self.start_date = None
            self.end_date = None
            self.dateEdit.setEnabled(False)
            self.dateEdit_2.setEnabled(False)

    def check_dateEdit(self):
        """检测dataedit
        """
        self.start_date = None
        self.end_date = None
        start_date = self.dateEdit.date()
        end_date = self.dateEdit_2.date()

        if start_date.isValid() and end_date.isValid():
            if start_date > end_date:
                self.dateEdit.blockSignals(True)
                self.dateEdit_2.blockSignals(True)
                self.dateEdit_2.setDate(QDate.currentDate())
                self.dateEdit.setDate(QDate.currentDate().addDays(-7))
                self.dateEdit.blockSignals(False)
                self.dateEdit_2.blockSignals(False)
                QMessageBox.warning(self, "警告", "结束时间不能早于开始时间！")
                return
        if start_date.isValid():
            self.start_date = start_date.toPython()
            self.start_date = combine_time(self.start_date, 0)
        if end_date.isValid():
            self.end_date = end_date.toPython()
            self.end_date = combine_time(self.end_date, 1)

    def set_comboBox(self):
        form_name_list = ["会员列表", "交易列表", "存单列表"]
        self.comboBox.addItems(form_name_list)

    def exp_excel(self):
        a = self.comboBox.currentIndex()
        try:
            if a == 0:
                df_form = export_member()
                df_form.columns = [
                    "会员ID",
                    "会员编号",
                    "姓名",
                    "联系方式",
                    "注册日期",
                    "初始余额",
                    "当前余额",
                    "消费总额",
                    "消费次数",
                    "最后一次消费时间",
                    "备注",
                    "创建时间",
                    "更新时间"
                ]
                df_form.drop(columns=["会员编号", "初始余额", "创建时间", "更新时间"], inplace=True)
                df_form['注册日期'] = df_form['注册日期'].dt.date
            elif a == 1:
                df_form = export_transaction()
                df_form.columns = [
                    "交易ID",
                    "会员ID",
                    "交易类型",
                    "交易金额",
                    "交易状态",
                    "备注",
                    "交易日期"
                ]
                df_form.drop(columns=["交易类型"], inplace=True)
                if self.start_date and self.end_date:
                    df_form = df_form[df_form["交易日期"].between(self.start_date, self.end_date)]

            elif a == 2:
                df_form = export_member_certificate()
                df_form.columns = [
                    "存单ID",
                    "会员ID",
                    "存单内容",
                    "存单状态",
                    "创建时间",
                    "状态核销时间"
                ]
            else:
                QMessageBox.warning(self, "提示", "请选择有效的导出类型")
                return
            print(df_form)
            if df_form.empty:
                QMessageBox.information(self, "提示", "当前选中类型无数据可导出")
                return
            file_path, _ = QFileDialog.getSaveFileName(
                self, "导出Excel", f"{self.comboBox.currentText()}", "Excel Files (*.xlsx *.xls)"
            )
            if not file_path:  # 用户取消选择
                return
            df_form.to_excel(file_path, index=False, engine="openpyxl")
            QMessageBox.information(self, "成功", f"数据已成功导出到:\n{file_path}")
        except Exception as e:
            print(e)
            QMessageBox.critical(self, "导出失败", f"错误原因:\n{str(e)}")

    def switch_combobox(self):
        """启用日期"""
        if self.comboBox.currentIndex() == 0:
            self.dateEdit.setEnabled(False)
            self.dateEdit_2.setEnabled(False)
            self.checkBox.setEnabled(False)
        elif self.comboBox.currentIndex() == 2:
            self.dateEdit.setEnabled(False)
            self.dateEdit_2.setEnabled(False)
            self.checkBox.setEnabled(False)
        elif self.comboBox.currentIndex() == 1:
            self.dateEdit.setEnabled(True)
            self.dateEdit_2.setEnabled(True)
            self.checkBox.setEnabled(True)




if __name__ == '__main__':
    app = QApplication([])
    win = ExportExcel()
    win.show()
    sys.exit(app.exec())
